<template>

  <div>
    <el-card body-style="padding: 8px 20px" style="margin-bottom: 5px;">
      <div slot="header" style="display: flex;justify-content: space-between">
        <div>流程进度</div>
        <div>
          <el-switch
            :active-value="2"
            :inactive-value="1" active-text="新版"
            inactive-text="旧版" style="margin-top: 5px;min-width: 120px;" v-model="useVersion"/>
        </div>
      </div>
      <div>
        <div>
          <el-progress :color="customColors" :percentage="percentage" :stroke-width="21" text-inside></el-progress>

        </div>

        <!--        <div style="display: flex;justify-content: flex-end;margin-top: 5px;">-->

        <!--        </div>-->

      </div>
    </el-card>

    <split-pane :default-percent='35'
                :max-percent='50'
                :min-percent='25'
                @resize="resize" split="vertical" style="height: 63vh">
      <template slot="paneL">

        <div style="display: flex;flex-direction: column">
          <template v-if="useVersion===1">
            <!--  流程列表  -->
            <el-card class="box-card" style="margin-right: 8px;">
              <div slot="header">
                <div style="display: flex;justify-content: space-between;align-items: center">
                  <span style="min-width: 64px;margin:0 5px;">流程列表</span>
                  <tech-route-select
                    :clearable="false"
                    @change="handleRouteTemplateChange"
                    size="small" v-model="productRelate.techRouteId"/>
                  <!--   <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button>-->
                </div>
              </div>

              <div
                style="display: flex;align-items: center;justify-content: center;height: 17vh"
                v-if="techRouteList.length === 0 && !productRelate.techRouteId">
                暂无流程列表🎁🎁✨🐱‍🏍✔🤷‍♀🎂😒👍💖
              </div>

              <!--      抽出功能组件    -->
              <!--     当前选择的变色,并且触点击事件改变     -->
              <div class="list-wrap" style="height: 17vh;overflow-y: scroll" v-else>
                <transition-group
                  appear
                  class="list-content" name="list-complete"
                  style="display: flex;flex-direction: column" tag="div">
                  <div
                    :key="techRoute.techId"
                    :style="currentItemIdx  === idx ?  'border: 2px solid #409EFF;' : ''"
                    @click="handleItemClick({item:techRoute,idx})"
                    class="list-item list-complete-item" style="
                transition: all .3s linear;
                background-color: rgb(217, 236, 255);
                border: 2px solid rgb(217, 236, 255);
                margin: 3px;
                height: 35px;
                border-radius: 3px;
                display: flex;
                padding: 0 5px;
                justify-content: space-between;
                align-items: center;
                cursor: pointer;"
                    v-for="(techRoute,idx) in techRouteList">
                    <span>{{techRoute.name}}</span>
                    <transition name="el-fade-in-linear">
                      <i
                        class="el-icon-success"
                        style="color: #409EFF;"
                        v-show="currentItemIdx  === idx"></i>
                    </transition>
                  </div>
                </transition-group>
              </div>
            </el-card>
            <!--  流程列表  -->
            <el-card class="box-card" style="margin-right: 8px;margin-top: 10px;">
              <div slot="header">
                <div style="display: flex;justify-content: space-between;align-items: center">
                  <span style="min-width: 64px;margin:0 5px;">工艺流程路线图</span>
                  <!--              <tech-route-select-->
                  <!--                @change="handleRouteTemplateChange"-->
                  <!--                size="small" v-model="productRelate.techRouteId"/>-->
                  <!--   <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button>-->
                </div>
              </div>

              <div
                style="display: flex;align-items: center;justify-content: center;height: 16vh"
                v-if="techRouteList.length === 0 && !productRelate.techRouteId">
                查找不到工艺流程路线图🎶🎶🎶
              </div>

              <div class="list-wrap" style="overflow-y: scroll;height: 16vh" v-else>
                <transition appear name="el-zoom-in-top">
                  <el-timeline style="margin: 15px;">
                    <el-timeline-item
                      :color=" currentItemIdx === idx ? '#409EFF' : '' "
                      :key="techRoute.techId"
                      v-for="(techRoute, idx) in techRouteList"
                    >
                      {{techRoute.name}}
                    </el-timeline-item>
                  </el-timeline>
                </transition>
              </div>

            </el-card>
          </template>

          <transition appear name="el-zoom-in-bottom" v-else-if="useVersion===2">
            <el-card style="margin-right: 8px;">

              <div slot="header">
                <div style="display: flex;justify-content: space-between;align-items: center">
                  <span style="min-width: 64px;margin:0 5px;">流程列表</span>
                  <tech-route-select
                    :clearable="false"
                    @change="handleRouteTemplateChange"
                    size="small" v-model="productRelate.techRouteId"/>
                  <!--   <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button>-->
                </div>
              </div>

              <div
                style="display: flex;align-items: center;justify-content: center;height: 48vh;"
                v-if="techRouteList.length === 0 && !productRelate.techRouteId">
                查找不到工艺流程路线图🎶🎶🎶
              </div>

              <el-timeline
                class="list-wrap"
                style="height: 48vh;overflow-y: scroll;padding: 5px;" v-else>
                <el-timeline-item
                  :color=" currentItemIdx === idx ? '#409EFF' : '' "
                  :key="techRoute.techId"
                  placement="top"
                  v-for="(techRoute, idx) in techRouteList">
                  <el-card
                    @click.native="handleItemClick({item:techRoute,idx})"
                    style="cursor: pointer">
                    <div style="display: flex;justify-content: space-between">

                      <span>
                         <i class="el-icon-caret-bottom" style="font-size: 21px;"></i>
                         <i class="el-icon-s-release" style="font-size: 21px;color: #6f7ad3"></i>
                        {{`工艺流程 step ${idx+1} => `}}
                      </span>
                      <el-tag>{{techRoute.name}}</el-tag>
                    </div>

                    <!--                  <p :style="currentItemIdx === idx ? 'color:#409EFF':''">-->
                    <!--                    {{techRoute.name}}-->
                    <!--                  </p>-->

                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </el-card>
          </transition>
        </div>

      </template>

      <template slot="paneR">
        <!--  材料选择table  -->
        <el-card class="box-card" style="margin-left: 8px;    height: 63vh;">
          <div slot="header" style="display: flex;justify-content: space-between;align-items: center">
            <span>工艺流程材料选择</span>
            <div>
              <!--              <transition name="el-fade-in-linear">-->
              <!--                <el-button-->
              <!--                  @click="ModifyProductMaterial"-->
              <!--                  type="success" >-->
              <!--                  保存物料-->
              <!--                </el-button>-->
              <!--              </transition>-->
              <el-button @click="handleAddMaterial" type="primary">
                新增物料
              </el-button>
            </div>
          </div>

          <azure-dynamic-table
            :column-des-objs="columnDesObjs"
            :data="tableData"
            :empty-text="tableEmptyText"
            :showSeq="true"
            class="list-table"
            height="41vh"
            v-loading="listLoading"
          >
            <template slot="formulaName" slot-scope="{scope:{row,$index}}">
              <div v-show="!row.isEdit">
                {{row['formulaName'] | isHasData}}
              </div>
              <formula-select
                :formulaName.sync="row.formulaName"
                v-model="row['formulaId']" v-show="row.isEdit"/>
            </template>

            <template slot="quantity" slot-scope="{scope:{row,$index}}">
              <div v-if="!row.isEdit">
                {{`${row.quantity }个`}}
              </div>
              <el-input-number
                :max="99"
                :min="1"
                size="mini"
                v-else v-model="row.quantity">
              </el-input-number>
            </template>

            <template slot="operator" slot-scope="{scope:{row,$index}}">
              <a-inline-edit
                :edit-form-data="row"
                :is-edit-flag.sync="row.isEdit"
                :submit-next="handleEditMaterial"
              />
              <el-popconfirm
                @confirm="handleDeleteMaterial({row,$index,tableData})"
                style="margin-left: 10px;"
                title="是否确定删除该产品的物料？"
                v-show="!row.isEdit">
                <AButton icon="el-icon-delete" slot="reference" type="info">
                  删除
                </AButton>
              </el-popconfirm>
            </template>

          </azure-dynamic-table>
        </el-card>

      </template>
    </split-pane>

    <!--  新增物料的 drawer  show 方法
          @update:checkedItemIds=""
    -->
    <add-material2-tech-route-drawer
      :backMaterialItemID="backMaterialItemID"
      :checked-item-ids="proxyCheckedItemIds"
      :dataHasChange.sync="dataHasChange"
      :routeHasMaterial="tableData"
      @checkedItemIdsChange="checkedItemIdsChange"
      ref="AddMaterial2TechRouteDrawer"/>
    <!--  submit 如何去重  -->

  </div>

</template>

<script>
  import splitPane from 'vue-splitpane'
  import TechRouteSelect from '@/components/ATheFridayClub/businessSelect/product/techRouteSelect'
  import {
    DeleteProductMaterial,
    ModifyProductLinkTechRoute,
    ModifyProductMaterial,
    QueryProductLinkTechRoute,
    QueryProductMateial,
    QueryTechRouteLink
  } from '@/api/productInformation'
  import { ERR_OK } from '@/utils/commons'
  import AzureDynamicTable from '@/components/ATheFridayClub/mDynamicTable/AzureDynamicTable'
  import AButton from '@/components/ATheFridayClub/AButton'
  import AInlineEdit from '@/components/ATheFridayClub/inlineEdit/AInlineEdit'
  import FormulaSelect from '@/components/ATheFridayClub/businessSelect/material/FormulaSelect'
  import AddMaterial2TechRouteDrawer from '@/views/baseproduct/components/halfComponent/AddMaterial2TechRouteDrawer'
  import { columnDesObjs } from './materialUtil'
  import tableMixin from '@/mixins/tableMixin'
  import { materialFactory, transformMaterialItemVO } from '@/views/baseproduct/components/halfComponent/materialUtil'
  import { customColors } from '@/utils/fridayClub/color'

  //  生产流程和生产流程材料编辑
  export default {
    name: 'flowMaterial',
    components: {
      AddMaterial2TechRouteDrawer,
      FormulaSelect,
      AInlineEdit,
      AButton,
      AzureDynamicTable,
      TechRouteSelect,
      splitPane
    },

    mixins: [tableMixin],
    computed: {
      percentage() {
        const curPos = this.currentItemIdx + 1
        console.log(curPos)
        console.log(this.techRouteList)

        if (curPos <= 0) {
          return 0
        }

        if (this.techRouteList.length <= 0) {
          return 100
        }

        //  |> parseInt
        return (curPos / this.techRouteList.length * 100) |> Math.ceil
      },
      tableEmptyText() {
        return Object.keys(this.currentItem).length ? '该工艺暂无配置物料 🎉🎉🎉🎉🎉' : '选择流程列表后配置材料👍😁👌'
      },
      proxyCheckedItemIds: {
        get() {
          // console.log('getter proxyCheckedItemIds >>>>>>>>>>>>')
          // console.log(this.tableData)
          return this.tableData.map(v => v.materialItemID)  //  materialItemId
        }
      }
    },

    provide() {
      return {
        deleteMaterial: this.deleteMaterial,
        ModifyProductMaterial: this.ModifyProductMaterial
      }
    },

    data() {
      return {
        dataHasChange: false,

        customColors,

        useVersion: 2,

        checkedIds: [],

        productRelate: {
          'productId': -1,
          'productLinkTechRouteId': null,
          'techRouteId': ''
        },

        techRouteList: Array.of(),
        currentItemIdx: -1,
        currentItem: {},

        tableData: Array.of(),
        columnDesObjs: Array.of(...columnDesObjs, { label: '操作', key: 'operator', width: 200 }),
        listLoading: false,

        backMaterialItemID: []
      }
    },
    watch: {

      //  查询工艺需要的物料
      currentItem: {
        deep: true,
        handler() {
          // if (){
          //
          // }
          this.QueryProductMateial()
        }
      },
      'productRelate.techRouteId'() {
        this.currentItem = {}
        this.getTechRouteLink()
        //  可能发生工艺换了,但是右侧的table没有刷新
      }
      // 'tableData.length'() {
      //   console.log('save 2 server >>>>>>>>')
      //
      //   //  调用保存关系图
      //   // this.getTechRouteLink()
      // }

    },
    methods: {

      // this.ModifyProductMaterial()

      //  过滤 要添加的 checkedItems 如果已经在table中 则忽略, 如果不再就添加
      //  没有分页,是一次全部家宅完成的,所以不用考虑枫叶问题
      checkedItemIdsChange(checkedIds, checkedItems) {
        const {
          currentItem: { techId },
          $route: { query: { ProductId } }
        } = this
        //  还有取消勾选的情况
        this.tableData = Array.of(...this.tableData, ...checkedItems.map(v =>
            v |> transformMaterialItemVO
              |> (obj => materialFactory({ ...obj, productId: ProductId, techId }))
          // |> debugLogger('all checked')
        ).filter(({ materialItemID }) => !(this.proxyCheckedItemIds.includes(materialItemID))))
          .filter(({ materialItemID }) => checkedIds.includes(materialItemID))

      },

      handleItemClick({ item, idx }) {
        this.currentItemIdx = idx
        this.currentItem = item
      },

      checkParam() {
        const {
          productRelate: {
            productId
            // productLinkTechRouteId,
            // techRouteId
          }, currentItem: { techId }
        } = this
        const { ProductId } = this.$route.query
        if (!ProductId) {
          throw new Error('产品ID不正确,请选择正确的产品😎🎁✨')
        }
        if (!techId) {
          throw new Error('请选择工艺路线.')
        }
      },

      //  新增产品物料 drawer show
      handleAddMaterial() {
        try {
          this.checkParam()
          // console.log(this.tableData); //  productMatetialId materialItemID

          this.backMaterialItemID = this.tableData.map(v => v.productMatetialId)
          this.$refs['AddMaterial2TechRouteDrawer'].handleAddHalfProduct()
        } catch (e) {
          this.$message.warning(e.message)
        }
      },

      //  行内编辑,编辑数量 和 产品的计算方式
      //  确认提交编辑
      async handleEditMaterial({ row, resolve, reject }) {
        try {
          const isSuc = await this.ModifyProductMaterial({ dataList: Array.of(row) })
          isSuc ? resolve() : reject()
        } catch (e) {
          console.log(e)
          reject()
        }
      },

      //  call save 2 server
      //  用户点击保存
      //  保存产线上的产品id
      /**
       * @return {boolean}
       */
      async ModifyProductMaterial({ dataList } = {}) {
        try {
          // const { tableData } = this
          this.dataHasChange = false
          const { Code, Result } = await ModifyProductMaterial(dataList)
          if (Code === ERR_OK) {
            this.$message.success('保存工艺物料信息成功')
            // this.$refs.drawer.closeDrawer()
            return true
          } else {
            this.$message.warning('保存工艺物料信息失败')
            return false
          }
        } catch (e) {
          console.log(e)
          return false
        }
      },

      //  真正的删除该物料,直接确定
      async handleDeleteMaterial({ row, $index, tableData }) {
        try {
          const { productMatetialId } = row
          await this.deleteMaterial({ ids: [productMatetialId] })
          this.tableData.splice($index, 1)
        } catch (e) {
          console.log(e)
        }
      },

      async deleteMaterial({ ids = [], showMsg = true } = {}) {
        const { Code } = await DeleteProductMaterial(ids)
        if (Code === ERR_OK) {
          showMsg && this.$message.success('删除组件工艺路线的材料成功')
          return true
        }
        showMsg && this.$message.success('删除组件工艺路线的材料失败')
        throw new Error('删除组件工艺路线的材料失败~~~')
      },

      //  查询关联关系模板
      async getProductRelate() {
        try {
          const { ProductId } = this.$route.query
          const { Code, Result } = await QueryProductLinkTechRoute({
            productId: ProductId,
            productLinkTechRouteId: 0  //  忽略的参数
          })
          if (Code === ERR_OK) {
            ({ [0]: this.productRelate = {} } = Result)
          } else {
            this.$message.warning('获取产品关联的模板路由失败 1 ')
          }
        } catch (e) {
          console.log(e)
          this.$message.warning('获取产品关联的模板路由失败 2 ')
        }
      },

      //  根据关系id查询路由的详细信息
      async getTechRouteLink() {
        try {
          const { techRouteId } = this.productRelate
          if (!techRouteId) {
            return
          }
          const { Code, Result } = await QueryTechRouteLink({
            techRouteId
          })
          if (Code === ERR_OK) {
            this.techRouteList = Result
          }
        } catch (e) {
          console.log(e)
        }
      },

      //  用户改变模板选择时自动保存当前选择的模板,并且刷新当前产品工艺数据,暂时不用btn保存方式
      //  目前采用了监听的方式
      //  用户点击某一个工艺流程时改变重新获取右侧的材料表和材料相关的配置
      handleSelectTechRoute() {

      },

      //  修改产品工艺路线流程
      async ModifyProductLinkTechRoute() {
        try {
          const {
            productRelate: {
              productId,
              productLinkTechRouteId,
              techRouteId
            }, currentItem: { techId }
          } = this

          const { ProductId } = this.$route.query

          const { Code } = await ModifyProductLinkTechRoute(Array.of({
            productId: ProductId,
            productLinkTechRouteId,
            techRouteId
          }))
          if (Code === ERR_OK) {
            // this.$message.success('保存成功')
          } else {
            this.$message.error('修改产品工艺路线流程失败(～￣▽￣)～')
          }
        } catch (e) {
          console.log(e)
        }
      },

      //  每次用户选择改变的时候就保存,只有用户点击才会派发事件
      async handleRouteTemplateChange() {
        console.log('handleRouteTemplateChange >>>>>>>>>')
        await this.ModifyProductLinkTechRoute()
      },

      //  resize split
      resize() {
        //  如果el-table 不能自适应可能需要调用 el-table 的 reLayout
      },

      //  查询某个工艺下的产品列表
      async QueryProductMateial() {
        try {
          const { ProductId } = this.$route.query
          const { productRelate: { productId }, currentItem: { techId } } = this
          if (!ProductId || !techId) {
            return
          }
          this.listLoading = true
          const { Code, Result } = await QueryProductMateial({
            productId: ProductId, techId
          })
          if (Code === ERR_OK) {
            this.tableData = Result
          }
        } catch (e) {
          console.log(e)
        } finally {
          this.listLoading = false
        }
      }
    },

    async created() {
      const loading = this.$loading({
        lock: true,
        text: '正在加载🤣🎶😜✔🐱‍🏍✨👍👌👌🎁🎉🎉🎉👏🤔',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      //  查询所有的模板,给用户选择配置流程 concurrent xhr
      //  根据级联关系id查到该组件的流程
      await this.getProductRelate()
      // await this.getTechRouteLink()
      loading.close()
    }

  }
</script>

<style lang="scss" scoped>
  @import "~@/styles/index.scss";

  .list-table {
    @include tableScrollBar()

  }

  .list-wrap {
    @include scrollBar()
  }

  .list-complete-item {
    transition: all 1s;
    display: inline-block;
    margin-right: 10px;
  }

  .list-complete-enter, .list-complete-leave-to
    /* .list-complete-leave-active for below version 2.1.8 */
  {
    opacity: 0;
    transform: translateY(30px);
  }

  .list-complete-leave-active {
    position: absolute;
  }

</style>
